// 全局函数
function showLoading(show) {
    const loading = document.getElementById('loading');
    if (show) {
        loading.classList.remove('d-none');
    } else {
        loading.classList.add('d-none');
    }
}

function logout() {
    const token = localStorage.getItem('token');

    if (token) {
        fetch('/api/auth/logout', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        }).finally(() => {
            localStorage.removeItem('token');
            window.location.href = '/login';
        });
    } else {
        window.location.href = '/login';
    }
}

// 页面加载时检查登录状态
document.addEventListener('DOMContentLoaded', function() {
    const token = localStorage.getItem('token');
    const currentPath = window.location.pathname;

    // 如果在登录页面但已登录，跳转到主页
    if (currentPath === '/login' && token) {
        window.location.href = '/';
    }

    // 如果不在登录页面且未登录，跳转到登录页
    if (currentPath !== '/login' && !token) {
        window.location.href = '/login';
    }
});

// 为所有API请求添加认证头
function getAuthHeaders() {
    const token = localStorage.getItem('token');
    return {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
    };
}